define([
    'jquery',
    'underscore',
    'backbone',
    'validator',
    'text!template/backyard/manage/docer_book_create.html',
    'view/backyard/manage/docer_book_list',
    'view/backyard/manage/parameter_error',
    'bootstrap'
], function(
        $,
        _,
        Backbone,
        validator,
        CreateTemplate,
        DocerListView,
        DocerError
    ){

    return Backbone.View.extend({
        el: '[bb-place-book]',
        template: _.template(CreateTemplate),

        events: {
            'click [bb-create]': 'create',
            'click [bb-create-submit]': 'submit',
            'click [bb-create-cancel]': 'cancel'
        },

        create: function() {
            this.$el.find('tfoot tr').hide();
            this.$el.find('tfoot').append(this.template());
        },

        submit: function() {
            var _this = this;

            var name = this.$el.find('[name="name"]').val();
            var version = this.$el.find('[name="version"]').val();
            var intro = this.$el.find('[name="intro"]').val();

            if (validator.isNull(name)) {
                new DocerError({
                    type: 'warning',
                    content: '名称不能为空'
                });
                _this.dismiss();
            } else {
                $.ajax({
                    url: '/api/backyard/manage/docer/book',
                    type: "POST",
                    dataType: 'json',
                    data: JSON.stringify({
                        name: name,
                        version: version,
                        intro: intro
                    }),
                    success: function (msg) {
                        if (msg == 'duplicate') {
                            new DocerError({
                                type: 'warning',
                                content: '该文档已经存在'
                            });
                            _this.dismiss();
                        } else if (msg == 'fail') {
                            new DocerError({
                                type: 'danger',
                                content: '添加出错，请稍后再试'
                            });
                            _this.dismiss();
                        } else {
                            _this.rerender();
                        }
                    }
                });
            }
        },

        cancel: function() {
            this.$el.find('[bb-create-cancel]').parents('tr').remove();
            this.$el.find('tfoot tr').show();
        },

        rerender: function() {
            new DocerListView();
            this.cancel();
        },

        dismiss: function() {
            this.$el.find('input').each(function() {
                this.click(function() {
                    $('.alert').remove();
                });
            });
        }
    });
});

